package com.mifengs.commonbase.net;

import com.alibaba.sdk.android.httpdns.HttpDnsService;
import com.mifengs.commonbase.base.BaseApplication;
import com.mifengs.commonbase.util.LogUtil;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.List;

import okhttp3.Dns;

/**
 * Created by lihaoqi on 2018/7/11.
 */

public class OkHttpDns implements Dns {

    private static final Dns SYSTEM = Dns.SYSTEM;
    HttpDnsService httpdns;//httpdns 解析服务
    private static OkHttpDns instance = null;


    private OkHttpDns() {
        this.httpdns = BaseApplication.getInstance().gethttpdns();
    }

    public static OkHttpDns getInstance() {
        if(instance == null) {
            instance = new OkHttpDns();
        }
        return instance;
    }

    @Override
    public List<InetAddress> lookup(String hostname) throws UnknownHostException {
        //通过异步解析接口获取ip
        String ip = httpdns.getIpByHostAsync(hostname);
        if(ip != null) {
            //如果ip不为null，直接使用该ip进行网络请求
            List<InetAddress> inetAddresses = Arrays.asList(InetAddress.getAllByName(ip));
            LogUtil.i("OkHttpDns", "inetAddresses:" + inetAddresses);
            return inetAddresses;
        }
        //如果返回null，走系统DNS服务解析域名
        return Dns.SYSTEM.lookup(hostname);
    }
}
